package com.example.recordingpen_datacollection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.recordingpen_datacollection.Utils.DateUtils.TimeJudgeUtils;
import com.example.recordingpen_datacollection.Utils.String.StringUtils;
import com.example.recordingpen_datacollection.entity.*;
import com.example.recordingpen_datacollection.entity.Vo.BusinesMaxTimeVo;
import com.example.recordingpen_datacollection.entity.Vo.BusinesVo;
import com.example.recordingpen_datacollection.entity.Vo.LimitDosageVo;
import com.example.recordingpen_datacollection.mapper.BusinessdataMapper;
import com.example.recordingpen_datacollection.result.exceptionhandler.JWException;
import com.example.recordingpen_datacollection.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xg
 * @since 2023-11-29
 */
@Service
public class BusinessdataServiceImpl extends ServiceImpl<BusinessdataMapper, Businessdata> implements BusinessdataService {
    @Autowired
    private UserMessageService userMessageService;

    @Autowired
    private LimitRatioService limitRatioService;
    @Autowired
    private LogQuotaService logQuotaService;
    @Autowired
    private LogEndtimeService logEndtimeService;

    @Override
    public void saveBusiness(BusinesVo businesVo, Integer defaultValue) {
        if (defaultValue == null || defaultValue <=0){
            defaultValue = 12;
        }
        Businessdata businessdata = new Businessdata();
        businessdata.setLoginId(businesVo.getLoginId());
        businessdata.setChargeType(businesVo.getChargeType());
        businessdata.setDosage(businesVo.getDosage());
        String monthTimeEnd = TimeJudgeUtils.addDayTime(TimeJudgeUtils.addNowMonthTimeV2("",defaultValue),1);
        businessdata.setEndTime(TimeJudgeUtils.strData(monthTimeEnd));
        String monthTimeMax =TimeJudgeUtils.addDayTime(TimeJudgeUtils.addNowMonthTimeV2("",18),1);
        businessdata.setMaxTime(TimeJudgeUtils.strData(monthTimeMax));
        boolean save = this.save(businessdata);
        if(!save){
            throw new JWException(500,"添加异常");
        }
    }

    @Override
    @Transactional
    public boolean updateDosage(Businessdata businessdata, QueryWrapper wrapper, Integer value) {
        boolean update = this.update(businessdata,wrapper);
        if (update && value != null){
            UserMessage userMess = userMessageService.getById(value);
            if(userMess != null){
                UserMessage userMessage = new UserMessage();
                userMessage.setUid(userMess.getUid());
                userMessage.setLimitQuantity(userMess.getLimitQuantity()-1);
                boolean update1 = userMessageService.updateById(userMessage);
                if(!update1){
                    throw new JWException(500,"数据操作异常");
                }
                return true;
            }
        } else if(update) {
            return true;
        }
        return false;
    }

    @Override
    public boolean alterBusinesMaxTime(Integer value, BusinesMaxTimeVo businesMaxTimeVo) {
        if(value !=null){
            UserMessage byId = userMessageService.getById(value);
            String maxTime = TimeJudgeUtils.strData(byId.getMaxTime());
            boolean judge = TimeJudgeUtils.judgeTime(maxTime, businesMaxTimeVo.getTime());
            if(!judge){
                throw new JWException(500,"超出最大时间");
            }
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("login_id",businesMaxTimeVo.getDevId());
        Businessdata one = this.getOne(wrapper);
        if(one  == null){
            throw new JWException(500,"设备不存在");
        }
        Businessdata businessdata = new Businessdata();
        businessdata.setId(one.getId());
        businessdata.setMaxTime(TimeJudgeUtils.strData(businesMaxTimeVo.getTime()));
        boolean update = this.updateById(businessdata);
        return update;
    }

    @Override
    @Transactional
    public boolean operateLimitDosage(LimitDosageVo limitDosageVo, UserMessage byId) {
        //查询设备
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("login_id",limitDosageVo.getDevId());
        Businessdata one = this.getOne(wrapper);
        if(one == null){
            throw new JWException(500,"设备不存在");
        }

        Businessdata businessdata = new Businessdata();
        Date MaxTime= null;
        if(limitDosageVo.getLimit() != null && limitDosageVo.getLimit()>0){
            //查询用户的配额比
            QueryWrapper wrapper1 = new QueryWrapper();
            wrapper1.eq("uid",byId.getUid());
            LimitRatio onelimit = limitRatioService.getOne(wrapper1);
            if(onelimit == null){
                throw new JWException(500,"数据存在异常请联系管理员");
            } else {
                if(onelimit.getRatio() == null || onelimit.getRatio()<=0){
                    throw new JWException(500,"数据存在异常请联系管理员");
                }
            }
            //修改用户额度转变额度
            UserMessage userMessage = new UserMessage();
            userMessage.setUid(byId.getUid());
            userMessage.setLimitQuantity((byId.getLimitQuantity() - limitDosageVo.getLimit()));
            boolean update = userMessageService.updateById(userMessage);
            if(!update){
                throw new JWException(500,"修改额度失败");
            }
            //log模块


            //减少额度转变为时间 月为单位
            String getEndTime = TimeJudgeUtils.strData(one.getMaxTime());
            boolean judgeTime = TimeJudgeUtils.judgeTime(TimeJudgeUtils.getNowDate(), getEndTime);
            if(!judgeTime){
                String addDayTime = TimeJudgeUtils.addMonthTime(getEndTime, (onelimit.getRatio() * limitDosageVo.getLimit()));
                Date addNowDayTime = TimeJudgeUtils.parseDate(addDayTime,"yyyy-MM-dd HH:mm:ss");
                businessdata.setMaxTime(addNowDayTime);
                MaxTime = addNowDayTime;
            } else {
//            Date nowDate = TimeJudgeUtils.parseDate(TimeJudgeUtils.getNowDate(), "yyyy-MM-dd HH:mm:ss");
                String s = TimeJudgeUtils.addNowDayTime(1) + " 23:59:59";
                String addDayTime = TimeJudgeUtils.addMonthTime(s, (onelimit.getRatio() * limitDosageVo.getLimit()));
                Date addNowDayTime = TimeJudgeUtils.parseDate(addDayTime, "yyyy-MM-dd HH:mm:ss");
//            businessdata.setStartTime(nowDate);
                businessdata.setMaxTime(addNowDayTime);
                MaxTime = addNowDayTime;
            }
            //添加额度日志模块
            LogQuota logQuota = new LogQuota();
            logQuota.setUid(byId.getUid());
            logQuota.setLoginId(limitDosageVo.getDevId());
            logQuota.setUseQuotas(limitDosageVo.getLimit());
            logQuota.setSurplusQuota((byId.getLimitQuantity() - limitDosageVo.getLimit()));
            logQuota.setSetMaxtime(MaxTime);
            logQuota.setFrontMaxtime(one.getMaxTime());
            boolean save = logQuotaService.save(logQuota);
            if(!save){
                throw new JWException(500,"QUO日志添加失败");
            }
            //------------------------------------
        } else {
            MaxTime = one.getMaxTime();
        }



        if(StringUtils.isNotEmpty(limitDosageVo.getEndTime())){
            if(TimeJudgeUtils.judgeTime(TimeJudgeUtils.strData(one.getStartTime()),limitDosageVo.getEndTime())){
                throw new JWException(500,"禁止低于起始时间");
            }

            boolean judgeTime1 = TimeJudgeUtils.judgeTime(TimeJudgeUtils.strData(MaxTime), limitDosageVo.getEndTime());
            if(!judgeTime1){
                System.out.println("b1: "+judgeTime1);
                throw new JWException(500,"超出最大时间");
            } else {
                businessdata.setEndTime(TimeJudgeUtils.strData(limitDosageVo.getEndTime()));
            }
        }
        businessdata.setId(one.getId());

        //修时间日志模块
        if(StringUtils.isNotEmpty(limitDosageVo.getEndTime())){
            LogEndtime logEndtime = new LogEndtime();
            logEndtime.setUid(byId.getUid());
            logEndtime.setLoginId(limitDosageVo.getDevId());
            logEndtime.setSetEndtime(TimeJudgeUtils.strData(limitDosageVo.getEndTime()));
            logEndtime.setFrontEndtime(one.getEndTime());
            boolean save = logEndtimeService.save(logEndtime);
            if(!save){
                throw new JWException(500,"END日志添加失败");
            }
        }
        //-----
        boolean update = this.updateById(businessdata);
        if(!update){
            throw new JWException(500,"修改异常");
        }



        return true;
    }
}
